package com.dure.hotmemory.scenes.jcxl;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.EmbossMaskFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.os.Build;
import android.text.TextUtils;

import com.dure.commonlib.util.PreferencesUtils;
import com.dure.hotmemory.R;
import com.dure.hotmemory.bean.Cell;
import com.dure.hotmemory.config.Constants;
import com.dure.hotmemory.controllers.Controller;
import com.dure.hotmemory.drawview.BaseSurfaceView;
import com.dure.hotmemory.scenes.BaseScene;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by dure on 2017/6/6.
 * 数字记忆
 */

public class JDSZYScene extends BaseScene {
    private final float topStateHeight;
    private List<String> digitsList = new ArrayList<>();
    private ArrayList<Integer> selectedDigitsIndexList = new ArrayList<>();
    private ArrayList<Integer> optionDigitsIndexList = new ArrayList<>();
    private ArrayList<Cell> optionDigitsCellList = new ArrayList<>();
    private boolean showNext = true;
    private int showDigitsNumber = 3, totalDigitsNumber;
    private int currentShowIndex;// 当前展示的图片index
    private int currentSelectIndex; // 当前待选择的index;
    private long startTime;
    Paint paint;
    private boolean showNextOption;
    private RectF frameRectF = new RectF();
    private Cell selectedCell;
    private long selectedStartTime,restartWaitTime;
    private Bitmap heartBitmap;
    private int heartCount = 3;
    private String finishInfo;
    private boolean roundFinish, win,canChose, restart, startDraw;
    private RectF leftBtnRectF, rightBtnRectF;// 训练结束对话框的左右按钮区域
    Controller controller;
    boolean newRecordGet;
    public String alias;
    private EmbossMaskFilter emboss;
    int[] colors = {Color.WHITE, Color.parseColor("#00BDFF")};

    public JDSZYScene(BaseSurfaceView baseSurfaceView) {
        super(baseSurfaceView);
        controller = new Controller(this);
        paint = new Paint();
        paint.setAntiAlias(true);
        Collections.addAll(digitsList, Constants.DIGITS);
        totalDigitsNumber = digitsList.size();
        heartBitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.heart);
        topStateHeight = baseSurfaceView.getWidth() * 0.12f;
        alias = PreferencesUtils.getString(activity, "current_alias");

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) {
            float[] direction = new float[] { 1, 1, 1 };
            // 设置环境光亮度
            float light = 0.5f;
            // 选择要应用的反射等级
            float specular = 10;// 这个参数更改没有看出效果上面的变化
            // 向mask应用一定级别的模糊
            float blur = 3;// 这个参数可以控制立体侧面的宽度
            emboss = new EmbossMaskFilter(direction, light, specular, blur);
            paint.setMaskFilter(emboss);
        }

        dataInited = true;
    }

    @Override
    public void handleData() {
        if (!dataInited) {
            return;
        }

        if (showNext) {
            showNext = false;
            if (showDigitsNumber > totalDigitsNumber) {
                showDigitsNumber = totalDigitsNumber;
            }
            canChose = false;
            roundFinish = false;
            showNextOption = false;
            currentShowIndex = 0;
            currentSelectIndex = 0;
            selectedDigitsIndexList = getRandomWordsIndex(showDigitsNumber, digitsList.size());
            startTime = System.currentTimeMillis();
            startDraw = true;
        }

        if (System.currentTimeMillis() - startTime > 3000 && currentShowIndex < selectedDigitsIndexList.size()) {
            startTime = System.currentTimeMillis();
            currentShowIndex++;

            if (currentShowIndex == selectedDigitsIndexList.size()) {
                showNextOption = true;
            }
        }

        if (showNextOption) {
            showNextOption = false;
            optionDigitsIndexList = getRandomWordsIndex(16, digitsList.size());

            // 判断optionImgIndexList里面是否含有当前要选择的图片， 没有则加进去
            int currentImgIndex = selectedDigitsIndexList.get(currentSelectIndex);
            if (!optionDigitsIndexList.contains(currentImgIndex)) {
                int randomReplaceIndex = (int) (Math.random() * optionDigitsIndexList.size());
                optionDigitsIndexList.remove(randomReplaceIndex);
                optionDigitsIndexList.add(randomReplaceIndex, currentImgIndex);
            }

            optionDigitsCellList = getCellList();
            canChose = true;
        }

        if (selectedCell != null) {
            // 获取当前需要被选择的卡片名称
            String imageName = digitsList.get(selectedDigitsIndexList.get(currentSelectIndex));
            if (TextUtils.equals(imageName, selectedCell.name)) {
                selectedCell.color = Color.GREEN;
                selectedCell.isCorrect = true;
            } else {
                selectedCell.color = Color.RED;
                selectedCell.isCorrect = false;

            }
            // 停顿1秒后切换下一张待选卡片
            if (System.currentTimeMillis() - selectedStartTime > 1000) {
                selectedStartTime = System.currentTimeMillis();
                selectedCell.color = Color.WHITE;
                selectedCell.selected = false;
                if (!selectedCell.isCorrect) {
                    heartCount--;

                    if (heartCount == 0) {// 准备切换下一轮
                        roundFinish = true;
                        finishInfo = "挑战失败， 请再接再励！";
                    }
                } else {// 选择正确
                    currentSelectIndex++;
                    if (currentSelectIndex < selectedDigitsIndexList.size()) {
                        canChose = false;
                        showNextOption = true;
                    } else {// 准备切换下一轮
                        win = true;
                        int oldBest = PreferencesUtils.getInt(activity, alias + ":best", 0);
                        if (showDigitsNumber > oldBest) {
                            newRecordGet = true;
                            PreferencesUtils.putInt(activity, alias + ":best", showDigitsNumber);
                        }
                    }
                }

                selectedCell.isCorrect = false;
                selectedCell = null;

            }
        }

        if (win && System.currentTimeMillis() - selectedStartTime > 1000) {
            selectedStartTime = System.currentTimeMillis();
            win = false;
            showDigitsNumber++;
            showNext = true;

        }else if (restart && System.currentTimeMillis() - restartWaitTime > 1000) {
            restart = false;
            heartCount = 3;
            showDigitsNumber = 3;
            showNext = true;
        }

    }

    private ArrayList<Integer> getRandomWordsIndex(int showNumber, int totalNumber) {
        ArrayList<Integer> indexList = new ArrayList<>();
        for (int i = 0; i < showNumber; i++) {
            int randomNum = (int) (Math.random() * totalNumber);

            while (indexList.contains(randomNum)) {
                randomNum = (int) (Math.random() * totalNumber);
            }

            indexList.add(randomNum);

        }

        return indexList;
    }

    private ArrayList<Cell> getCellList() {
        ArrayList<Cell> cellList = new ArrayList<>();

        float frameSize = baseSurfaceView.getWidth() * 0.8f;
        float perImageSize = frameSize / 4;
        float padding = baseSurfaceView.getWidth() * 0.2f / 5;
        float frameTop = baseSurfaceView.getHeight() / 2 - frameSize / 2 - padding;
        frameRectF = new RectF(padding, frameTop, baseSurfaceView.getWidth() - padding, frameTop + frameSize + 2 * padding);
        for (int i = 0; i < optionDigitsIndexList.size(); i++) {
            int row = i / 4;
            int column = i % 4;
            float dstLeft = padding * (column + 1) + column * perImageSize;
            float dstTop = padding * (row + 1) + row * perImageSize + frameTop;
            float dstRight = dstLeft + perImageSize;
            float dstBottom = dstTop + perImageSize;

            String wordsName = digitsList.get(optionDigitsIndexList.get(i));

            RectF dstRect = new RectF(dstLeft, dstTop, dstRight, dstBottom);

            Cell cell = new Cell();
            cell.index = i;
            cell.name = wordsName;
            cell.rectF = dstRect;
            cell.color = Color.WHITE;

            cellList.add(cell);
        }

        return cellList;
    }

    @Override
    public void handleDraw(Canvas canvas) {
        if (!dataInited) {
            return;
        }

        if (currentShowIndex < selectedDigitsIndexList.size()) {// 绘制待选择的图片
            drawScanningWords(canvas);
        } else {// 绘制选择图片界面

            if (roundFinish){
                drawFinishDialog(canvas);
            }else if (startDraw){
                drawSelectingWords(canvas);
                drawHeart(canvas);
                drawScore(canvas);
            }
        }


    }

    private void drawScanningWords(Canvas canvas) {
        String wordsName = digitsList.get(selectedDigitsIndexList.get(currentShowIndex));
        
        int centerX = canvas.getWidth() / 2;
        int centerY = canvas.getHeight() / 2;
        int showingSize = centerX;
        int dstLeft = centerX - showingSize / 2;

        int dstTop = centerY - showingSize / 2;
        int dstRight = centerX + showingSize / 2;
        int dstBottom = centerY + showingSize / 2;
        RectF dstRect = new RectF(dstLeft, dstTop, dstRight, dstBottom);

        paint.setColor(Color.WHITE);
        float arc = dstRect.width() / 10;
        canvas.drawRoundRect(dstRect, arc, arc, paint);

        float wordsSize = 0;
        if (wordsName.length() <= 2){
            wordsSize = showingSize * 0.8f / 2;
        }else{
            wordsSize = showingSize * 0.8f / wordsName.length();
        }
        paint.setTextSize(wordsSize);
        float wordsWidth = paint.measureText(wordsName);
        float wordsLeft = centerX - wordsWidth / 2;
        float wordsBottom  = centerY + wordsSize / 3;
        paint.setColor(Color.parseColor("#00BDFF"));
        canvas.drawText(wordsName, wordsLeft, wordsBottom, paint);
    }

    private void drawSelectingWords(Canvas canvas) {
        for (int i = 0; i < optionDigitsCellList.size(); i++) {
            Cell cell = optionDigitsCellList.get(i);

            paint.setColor(cell.color);
            float arc = cell.rectF.width() / 10;
            canvas.drawRoundRect(cell.rectF, arc, arc, paint);

            float showingSize = cell.rectF.width();
            String wordsName = cell.name;
            float wordsSize = 0;
            if (wordsName.length() <= 2){
                wordsSize = showingSize * 0.8f / 2;
            }else{
                wordsSize = showingSize * 0.8f / wordsName.length();
            }
            paint.setTextSize(wordsSize);
            float cellCenterX = cell.rectF.left + cell.rectF.width() / 2;
            float cellCenterY = cell.rectF.top + cell.rectF.height() / 2;
            float wordsWidth = paint.measureText(wordsName);
            float wordsLeft = cellCenterX - wordsWidth / 2;
            float wordsBottom  = cellCenterY + wordsSize / 3;
            paint.setColor(Color.parseColor("#00BDFF"));
            canvas.drawText(wordsName, wordsLeft, wordsBottom, paint);
        }
    }

    private void drawHeart(Canvas canvas) {
        Rect srcRect = new Rect(0, 0, heartBitmap.getWidth(), heartBitmap.getHeight());

        float dstHeartSize = topStateHeight * 0.8f;
        float leftPadding = topStateHeight * 0.2f;
        float topPadding = leftPadding;
        for (int i = 0; i < heartCount; i++) {
            float dstLeft = leftPadding * (i + 1) + i * dstHeartSize;
            float dstTop = topPadding;
            float dstRight = dstLeft + dstHeartSize;
            float dstBottom = dstTop + dstHeartSize;
            RectF dstRect = new RectF(dstLeft, dstTop, dstRight, dstBottom);

            canvas.drawBitmap(heartBitmap, srcRect, dstRect, null);
        }
    }

    private void drawScore(Canvas canvas) {

        String scoreStr = String.format("%d/%d", currentSelectIndex, selectedDigitsIndexList.size());
        String recordStr = String.format("Best:%d", PreferencesUtils.getInt(activity, alias + ":best", 0));

        float textSize = topStateHeight * 0.6f;
        paint.setTextSize(textSize);

        float scoreWidth = paint.measureText(scoreStr);
        float contentWidth = paint.measureText(recordStr);
        float rightPadding = topStateHeight * 0.2f;
        float topPadding = rightPadding;

        float contentLeft = canvas.getWidth() - rightPadding - contentWidth;
        float contentBottom = topPadding + textSize;

        paint.setColor(Color.WHITE);
        canvas.drawText(recordStr, contentLeft, contentBottom, paint);

        float scoreLeft = canvas.getWidth() / 2 - scoreWidth / 2;
        float scoreBottom = contentBottom;
        canvas.drawText(scoreStr, scoreLeft, scoreBottom, paint);
    }

    private void drawFinishDialog(Canvas canvas) {
        String infoStr = finishInfo;
        String exitStr = "退出";
        String continueStr = "重来";

        float dialogWidth = canvas.getWidth() * 0.8f;
        float dialogHeight = dialogWidth * 0.6f;
        float infoPartHeight = dialogHeight * 0.7f;
        float btnPartHeight = dialogHeight * 0.3f;

        float infoTextSize = dialogWidth * 0.85f / infoStr.length();

        // 绘制dialog frame
        float dialogLeft = canvas.getWidth() / 2 - dialogWidth / 2;
        float dialogTop = canvas.getHeight() / 2 - dialogHeight / 2;
        float dialogRight = canvas.getWidth() / 2 + dialogWidth / 2;
        float dialogBottom = canvas.getHeight() / 2 + dialogHeight / 2;
        RectF dialogRectF = new RectF(dialogLeft, dialogTop, dialogRight, dialogBottom);
        paint.setColor(Color.WHITE);
        float arc = dialogRectF.width() / 15;

        LinearGradient lg = new LinearGradient(dialogRectF.width() /2, 0, dialogRectF.width() /2, dialogRectF.height(), colors, null, Shader.TileMode.MIRROR);
        paint.setShader(lg);
        canvas.drawRoundRect(dialogRectF, arc, arc, paint);
        paint.setShader(null);

        // 绘制info
        paint.setTextSize(infoTextSize);
        float infoWidth = paint.measureText(infoStr);
        float infoLeft = canvas.getWidth() / 2 - infoWidth / 2;
        float infoBottom = dialogTop + infoPartHeight / 2 + infoTextSize / 2;
        paint.setColor(Color.RED);
        canvas.drawText(infoStr, infoLeft, infoBottom, paint);

        float btnWidth = dialogWidth * 0.3f;
        float btnHeight = btnWidth / 2.5f;
        float btnTextSize = btnHeight * 0.6f;

        // 绘制左边btn
        float leftBtnLeft = canvas.getWidth() / 2 - dialogWidth / 4 - btnWidth / 2;
        float leftBtnBottom = dialogBottom - btnPartHeight / 2 + btnHeight / 2;
        float leftBtnRight = leftBtnLeft + btnWidth;
        float leftBtnTop = leftBtnBottom - btnHeight;
        leftBtnRectF = new RectF(leftBtnLeft, leftBtnTop, leftBtnRight, leftBtnBottom);
        arc = leftBtnRectF.width() / 15;
        paint.setColor(Color.parseColor("#00BDFF"));
        canvas.drawRoundRect(leftBtnRectF, arc, arc, paint);

        paint.setTextSize(btnTextSize);
        float exitStrWidth = paint.measureText(exitStr);
        float exitLeft = leftBtnLeft + btnWidth / 2 - exitStrWidth / 2;
        float exitBottom = leftBtnBottom - btnHeight * 0.3f;
        paint.setColor(Color.WHITE);
        canvas.drawText(exitStr, exitLeft, exitBottom, paint);

        // 绘制右边btn
        float rightBtnLeft = canvas.getWidth() / 2 + dialogWidth / 4 - btnWidth / 2;
        float rightBtnBottom = leftBtnBottom;
        float rightBtnRight = rightBtnLeft + btnWidth;
        float rightBtnTop = leftBtnTop;
        rightBtnRectF = new RectF(rightBtnLeft, rightBtnTop, rightBtnRight, rightBtnBottom);
        arc = rightBtnRectF.width() / 15;
        paint.setColor(Color.parseColor("#00BDFF"));
        canvas.drawRoundRect(rightBtnRectF, arc, arc, paint);

        paint.setTextSize(btnTextSize);
        float continueStrWidth = paint.measureText(continueStr);
        float continueLeft = rightBtnLeft + btnWidth / 2 - continueStrWidth / 2;
        float continueBottom = rightBtnBottom - btnHeight * 0.3f;
        paint.setColor(Color.WHITE);
        canvas.drawText(continueStr, continueLeft, continueBottom, paint);
    }

    @Override
    public void handleDown(PointF pointF) {
        if (!canChose){
            return;
        }
        if (selectedCell == null && !roundFinish) {
            // 先判断点击位置是否在frame内
            if (frameRectF.contains(pointF.x, pointF.y)) {
                // 再判断点击了哪个卡片
                for (int i = 0; i < optionDigitsCellList.size(); i++) {
                    Cell cell = optionDigitsCellList.get(i);
                    if (cell.rectF.contains(pointF.x, pointF.y)) {
                        selectedStartTime = System.currentTimeMillis();
                        cell.selected = true;
                        selectedCell = cell;
                        break;
                    }
                }
            }
        }

        if (roundFinish){
            if (leftBtnRectF.contains(pointF.x, pointF.y)){
                roundFinish = false;
                activity.backToLastScene();
            }else if (rightBtnRectF.contains(pointF.x, pointF.y)){
                restart = true;
                startDraw = false;
                roundFinish = false;
                restartWaitTime = System.currentTimeMillis();
            }
        }
    }

    @Override
    public void handleUp(PointF pointF) {
        super.handleUp(pointF);
    }

    @Override
    public void handleBack() {
        if (PreferencesUtils.getBoolean(activity, "login_success")){
            if (newRecordGet) {
                int level = PreferencesUtils.getInt(activity, alias + ":best", 0);
                controller.uploadTrainingData(String.valueOf(level), alias);
            }
        }
    }
}
